package asfabdesk.apresentacao;

import asfabdesk.dominio.Convenio;
import asfabdesk.dominio.Data;
import asfabdesk.dominio.EmpresaConveniada;
import asfabdesk.dominio.Moeda;
import asfabdesk.presistencia.DAO;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelaConvenio.java
 *
 * Created on 09/10/2010, 12:22:59
 */
/**
 *
 * @author Mathias
 */
public class TelaConvenio extends javax.swing.JInternalFrame {

    public Convenio convenio = new Convenio();
    public boolean semPagamento = false;

    /** Creates new form TelaConvenio */
    public TelaConvenio() throws SQLException {
        initComponents();
        configurarTela();
    }

    public void configurarTela() throws SQLException {
        configurarComboEmpresas();
    }

    public void configurarComboEmpresas() throws SQLException {
        java.util.List empresas = (new DAO()).listar(EmpresaConveniada.class);
        for (int i = 0; i < empresas.size(); i++) {
            String nome = ((EmpresaConveniada) empresas.get(i)).getNomeFantasia();
            comboEmpresa.addItem(nome);
        }
        comboEmpresa.addItem("");
        comboEmpresa.setSelectedItem("");
    }

    public void salvarConvenio() {
        if (verificarCampos()) {
            if (verificarUniques()) {
                convenio = povoarConvenio();
                try {
                    new DAO().salvar(convenio);
                    JOptionPane.showMessageDialog(null, "Convênio Cadastrado com Sucesso'.", "Sucesso", 1);
//                    configurarParaCadastroSalvo();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Ops, ocorreu um erro durante o cadastro'.", "Ops,erro!", 0);
                    e.printStackTrace();
                }
            }
        }
    }

    public Convenio povoarConvenio() {

        try {
            Convenio conv = new Convenio();
            conv.setNome(txtNome.getText().toUpperCase());
            try {
                conv.setDataInicio(txtinicio.getText());
                conv.setDataTermino(txtTermino.getText());
            } catch (Exception ex) {
            }

            conv.setDescricao(txtDescricao.getText());
            if (txtCarencia.getText().equals("  ")) {
                conv.setCarencia(0);
            } else {
                conv.setCarencia(Integer.parseInt(txtCarencia.getText()));
            }
            conv.setFormaPgt(comboPagamento.getSelectedIndex());
            conv.setValor(new Moeda(txtValor.getText()).doubleValue());
            EmpresaConveniada empresa = new EmpresaConveniada();
            empresa = (new DAO().localizar(EmpresaConveniada.class, "EmpresaPorNomeFantasia", comboEmpresa.getSelectedItem().toString()));
            conv.setEmpresa(empresa);
            Date data = new Date();
            String dataString = (String) new Data().ConverteDataHoraDateStringBra(data);
            try {
                data = new Data().ConverteDataHoraStringDate(dataString);
            } catch (ParseException ex) {
                Logger.getLogger(TelaConvenio.class.getName()).log(Level.SEVERE, null, ex);
            }
            conv.setDataRegistro(data);
            conv.setUsuarioCadastrante(TelaLogin.usuario);
            return conv;

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public boolean verificarCampos() {
        boolean retorno = true;
        StringBuffer campos = new StringBuffer();
        String str = "";

        if (txtNome.getText().equals("")) {
            str = "(Nome) ";
            campos.append(str);
            retorno = false;
        }

        if (comboEmpresa.getSelectedItem().toString().equals("")) {
            str = " (Empresa) ";
            campos.append(str);
            retorno = false;
        }

        if (retorno == false) {
            JOptionPane.showMessageDialog(null, "Ops, você não preencheu o(s) seguinte(s) campo(s) obrigatório(s): " + '\n' + campos, "Campos Obrigatórios.", 2);
        }
        return retorno;
    }

    public boolean verificarUniques() {
        StringBuffer campos = new StringBuffer();
        String string = "";
        boolean retorno = true;

        if (new DAO().localizar(Convenio.class, "ConvenioPorNome", txtNome.getText()) != null) {
            string = " (Nome do Convênio= " + txtNome.getText() + ") ";
            campos.append(string);
            retorno = false;
        }

        if (retorno == false) {
            JOptionPane.showMessageDialog(null, "Ops, já existe um Convênio com esse nome: " + '\n' + campos, "Campos Únicos.", 2);
        }
        return retorno;
    }

    public void limparCampos() {
        comboEmpresa.setSelectedIndex(0);
        txtNome.setText("");
        txtinicio.setText("");
        txtTermino.setText("");
        txtCarencia.setText("");
        ckSemPagamento.setSelected(false);
        beneficioSemPagamento();
        txtDescricao.setText("");
    }

    public void beneficioSemPagamento() {
        if (ckSemPagamento.isSelected()) {
            comboPagamento.setSelectedIndex(0);
            comboPagamento.setEnabled(false);
            txtValor.setText("0,00");
            txtValor.setEditable(false);
            semPagamento = true;
        } else {
            comboPagamento.setSelectedIndex(1);
            comboPagamento.setEnabled(true);
            txtValor.setText("0,00");
            txtValor.setEditable(true);
            semPagamento = false;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fundo = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        txtNome = new javax.swing.JTextField();
        txtinicio = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        comboEmpresa = new javax.swing.JComboBox();
        jLabel18 = new javax.swing.JLabel();
        txtTermino = new javax.swing.JFormattedTextField();
        jLabel19 = new javax.swing.JLabel();
        ckSemPagamento = new javax.swing.JCheckBox();
        jPanel8 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        comboPagamento = new javax.swing.JComboBox();
        txtValor = new javax.swing.JFormattedTextField();
        jLabel13 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDescricao = new javax.swing.JTextPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        bfInferior1 = new javax.swing.JToolBar();
        btnSalvar = new javax.swing.JButton();
        btnAtivaInativa = new javax.swing.JButton();
        btnNovo = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel20 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        txtCarencia = new javax.swing.JFormattedTextField();

        setClosable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(asfabdesk.apresentacao.AsfabDeskApp.class).getContext().getResourceMap(TelaConvenio.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setFrameIcon(resourceMap.getIcon("Form.frameIcon")); // NOI18N
        setName("Form"); // NOI18N

        fundo.setBackground(resourceMap.getColor("fundo.background")); // NOI18N
        fundo.setName("fundo"); // NOI18N

        jPanel9.setBackground(resourceMap.getColor("jPanel5.background")); // NOI18N
        jPanel9.setName("jPanel5"); // NOI18N
        jPanel9.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        txtNome.setText(resourceMap.getString("txtNomeDoConvenio.text")); // NOI18N
        txtNome.setName("txtNomeDoConvenio"); // NOI18N
        jPanel9.add(txtNome, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, 190, -1));

        try {
            txtinicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtinicio.setName("txtDataInicial"); // NOI18N
        jPanel9.add(txtinicio, new org.netbeans.lib.awtextra.AbsoluteConstraints(207, 90, 80, -1));

        jLabel7.setName("jLabel3"); // NOI18N
        jPanel9.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(214, 56, -1, -1));

        jLabel10.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel10.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel10.setName("jLabel8"); // NOI18N
        jPanel9.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 70, -1, -1));

        comboEmpresa.setName("cbEmpresa"); // NOI18N
        jPanel9.add(comboEmpresa, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 180, -1));

        jLabel18.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel18.setText(resourceMap.getString("jLabel14.text")); // NOI18N
        jLabel18.setName("jLabel14"); // NOI18N
        jPanel9.add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));

        try {
            txtTermino.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtTermino.setName("txtValidade"); // NOI18N
        jPanel9.add(txtTermino, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 90, 70, -1));

        jLabel19.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel19.setText(resourceMap.getString("jLabel16.text")); // NOI18N
        jLabel19.setName("jLabel16"); // NOI18N
        jPanel9.add(jLabel19, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 70, -1, -1));

        ckSemPagamento.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        ckSemPagamento.setText(resourceMap.getString("checkBeneficioNaoPagavel.text")); // NOI18N
        ckSemPagamento.setName("checkBeneficioNaoPagavel"); // NOI18N
        ckSemPagamento.setOpaque(false);
        ckSemPagamento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ckSemPagamentoActionPerformed(evt);
            }
        });
        jPanel9.add(ckSemPagamento, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 120, -1, -1));

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel4.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), resourceMap.getColor("jPanel4.border.titleColor"))); // NOI18N
        jPanel8.setName("jPanel4"); // NOI18N
        jPanel8.setOpaque(false);
        jPanel8.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel11.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel11.setName("jLabel5"); // NOI18N
        jPanel8.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 59, -1, -1));

        comboPagamento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Desconto em folha", "ASFAB", "Empresa" }));
        comboPagamento.setName("cbTipoDePagamento"); // NOI18N
        jPanel8.add(comboPagamento, new org.netbeans.lib.awtextra.AbsoluteConstraints(18, 33, -1, -1));

        txtValor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###,###,##0.00"))));
        txtValor.setName("txtValor"); // NOI18N
        jPanel8.add(txtValor, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 79, 95, -1));

        jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
        jLabel13.setName("jLabel13"); // NOI18N
        jPanel8.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(18, 82, -1, -1));

        jPanel9.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 150, 150, 120));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel2.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), resourceMap.getColor("jPanel2.border.titleColor"))); // NOI18N
        jPanel2.setName("jPanel2"); // NOI18N
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        txtDescricao.setName("txtDescricao"); // NOI18N
        jScrollPane2.setViewportView(txtDescricao);

        jPanel2.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 22, 270, 80));

        jPanel9.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 150, 290, 120));

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setForeground(resourceMap.getColor("jLabel1.foreground")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N
        jPanel9.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 70, -1, -1));

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setIcon(resourceMap.getIcon("jLabel2.icon")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jLabel2.setName("jLabel2"); // NOI18N
        jPanel9.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 0, -1, -1));

        bfInferior1.setBackground(resourceMap.getColor("bfInferior1.background")); // NOI18N
        bfInferior1.setFloatable(false);
        bfInferior1.setName("bfInferior1"); // NOI18N

        btnSalvar.setForeground(resourceMap.getColor("btnSalvar.foreground")); // NOI18N
        btnSalvar.setIcon(resourceMap.getIcon("btnSalvar.icon")); // NOI18N
        btnSalvar.setText(resourceMap.getString("btnSalvar.text")); // NOI18N
        btnSalvar.setFocusable(false);
        btnSalvar.setName("btnSalvar"); // NOI18N
        btnSalvar.setOpaque(false);
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });
        bfInferior1.add(btnSalvar);

        btnAtivaInativa.setForeground(resourceMap.getColor("btnAtivaInativa.foreground")); // NOI18N
        btnAtivaInativa.setIcon(resourceMap.getIcon("btnAtivaInativa.icon")); // NOI18N
        btnAtivaInativa.setText(resourceMap.getString("btnAtivaInativa.text")); // NOI18N
        btnAtivaInativa.setName("btnAtivaInativa"); // NOI18N
        btnAtivaInativa.setOpaque(false);
        bfInferior1.add(btnAtivaInativa);

        btnNovo.setForeground(resourceMap.getColor("btnNovo.foreground")); // NOI18N
        btnNovo.setIcon(resourceMap.getIcon("btnNovo.icon")); // NOI18N
        btnNovo.setText(resourceMap.getString("btnNovo.text")); // NOI18N
        btnNovo.setFocusable(false);
        btnNovo.setName("btnNovo"); // NOI18N
        btnNovo.setOpaque(false);
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        bfInferior1.add(btnNovo);

        jPanel9.add(bfInferior1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 290, 450, -1));

        jSeparator1.setForeground(resourceMap.getColor("jSeparator1.foreground")); // NOI18N
        jSeparator1.setName("jSeparator1"); // NOI18N
        jPanel9.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 280, 451, 10));

        jLabel20.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel20.setText(resourceMap.getString("jLabel20.text")); // NOI18N
        jLabel20.setName("jLabel20"); // NOI18N
        jPanel9.add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));

        jLabel12.setFont(resourceMap.getFont("jLabel12.font")); // NOI18N
        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N
        jPanel9.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 70, -1, -1));

        try {
            txtCarencia.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtCarencia.setName("txtCarencia"); // NOI18N
        jPanel9.add(txtCarencia, new org.netbeans.lib.awtextra.AbsoluteConstraints(368, 90, 90, -1));

        javax.swing.GroupLayout fundoLayout = new javax.swing.GroupLayout(fundo);
        fundo.setLayout(fundoLayout);
        fundoLayout.setHorizontalGroup(
            fundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fundoLayout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        fundoLayout.setVerticalGroup(
            fundoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fundoLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fundo, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(fundo, javax.swing.GroupLayout.PREFERRED_SIZE, 362, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ckSemPagamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ckSemPagamentoActionPerformed
        beneficioSemPagamento();
    }//GEN-LAST:event_ckSemPagamentoActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        salvarConvenio();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        limparCampos();
    }//GEN-LAST:event_btnNovoActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToolBar bfInferior1;
    private javax.swing.JButton btnAtivaInativa;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JCheckBox ckSemPagamento;
    private javax.swing.JComboBox comboEmpresa;
    private javax.swing.JComboBox comboPagamento;
    private javax.swing.JPanel fundo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JFormattedTextField txtCarencia;
    private javax.swing.JTextPane txtDescricao;
    private javax.swing.JTextField txtNome;
    private javax.swing.JFormattedTextField txtTermino;
    private javax.swing.JFormattedTextField txtValor;
    private javax.swing.JFormattedTextField txtinicio;
    // End of variables declaration//GEN-END:variables
}
